//
//  AppDelegate.m
//  YueYueSpecailCarDriver
//
//  Created by Qianxia on 2017/1/3.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "AppDelegate.h"
#import <ConnectionBaseManager/ConnectionBaseManager.h>
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <QXYueYueModels/QXYueYueModels-umbrella.h>
#import <QXSocketManager/QXSocketManager.h>
#import "DLLApiManager.h"
#import <QXDataManager/QXDataManager.h>
#import "LocationManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "HeaderMacro.h"
#import "DLLApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "PaymentMethodVC.h"
#import "HeaderMacro.h"
#import <AFNetworking/AFNetworking.h>
#import <Bugly/Bugly.h>
#import "iflyMSC/IFlyMSC.h"
#import "ConfigureKeyHeader.h"
#import "BootPageVC.h"
#import "NotificationNameManager.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <ConnectionBaseManager/ConnectionBaseManager.h>
#import "AppManager.h"
#import "AppInfoModel.h"
#import "MapManager.h"
@interface AppDelegate ()<WXApiDelegate>

#pragma mark - 强制更新
/// app是否可用
@property (assign, nonatomic) BOOL isUsed;
/// 更新警告框
@property (strong, nonatomic) UIAlertView *updateAlertView;
/// 下载地址
@property (copy, nonatomic) NSString *downloadUrl;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /// 配置app信息
    [[AppManager shareManager] setAppWithDriverType:(DriverTypeSpecialCar) appDriverOrgan:(AppDriverOrganNameOfYueYue)];
    /// 设置使用的地图的类型
    [[MapManager shareManager] setMapType:MapTypeMapBox];

    [self configureBootPageWithApplication:(UIApplication *)application];
    [self configureDefaultAttributes];
    
    // 更新或强制更新
    [self mandatoryUpgrade];
    return YES;
}

- (void)configureDefaultAttributes {
 
    // 发布的时候去掉
//    [Bugly startWithAppId:@"4c665cfb35"];
//    [Bugly startWithAppId:@"d049e60319"];
    
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    
    // 设置配置工程
    [self generalConfigure];
    
    // 配置基础网络设置
    [ConnectionBaseManager setAppId:[QXDataManager getValueForKey:QXAppId]];
    [ConnectionBaseManager setRequestKey:QXRequestKey];
    
    // 设置长连接
    [QXSocketManager setUrl:[QXDriverConfiguration socketBaseUrlString]];
    
    // 设置主颜色
    [QXDataManager saveValue:@"#FFC225" forKey:AppMainDriverColorKey];
    
    // 设置按钮颜色
    [QXDataManager saveValue:@"#4F5A67" forKey:AppDriverButtonColorKey];
    
    
    
    // 配置网络地址
    [self getConfigInfoFromHost];
    
    // 检测网络状态
    [self monitorNetWorkingState];
    
    // 配置讯飞网络播报
    [self configureIflyMSC];
}

- (void)generalConfigure {
    AppInfoModel *appInfoModel = [[AppManager shareManager] getAppInfo];
    // 设置app名字
//    [QXDataManager saveValue:QXAppNameValue forKey:QXAppName];
    [QXDataManager saveValue:appInfoModel.AppName forKey:QXAppName];
    
    // 初始化网络配置
//    [QXDataManager saveValue:QXAppIdValue forKey:QXAppId];
    [QXDataManager saveValue:appInfoModel.AppId forKey:QXAppId];
    
    // 配置运营企业名称
    [QXDataManager saveValue:[NSString stringWithFormat:@"%ld" , (unsigned long)appInfoModel.AppDriverOrgan] forKey:QXAppManagerDriverOrganName];
    
//    [QXDataManager saveValue:QXDriverTypeValue forKey:QXDriverTypeKey]; // 设置司机类型 1: 出租车 , 2: 专车 , 3: 跨城拼车 , 4: 快车,5:货的,6:骑手,7:搬家
    QXYYUserDriverModel*driverMdoel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (driverMdoel) {
        
        appInfoModel.AppDriverType = driverMdoel.type;
    }
    
    [QXDataManager saveValue:[NSString stringWithFormat:@"%ld" , appInfoModel.AppDriverType] forKey:QXDriverTypeKey];
    
    
    // 高德地图
//    [QXDataManager saveValue:QXGKKey forKey:AMap_AppKey];
//    [LocationManager shareManager].mapAPIKey = QXGKKey;
//    [AMapServices sharedServices].apiKey = QXGKKey;
    [QXDataManager saveValue:appInfoModel.AppGDMapKey forKey:AMap_AppKey];
    [LocationManager shareManager].mapAPIKey = appInfoModel.AppGDMapKey;
    [AMapServices sharedServices].apiKey = appInfoModel.AppGDMapKey;
    [AMapServices sharedServices].enableHTTPS = YES;
    
    // 地图key设置后初始化一次定位管理器
    [LocationManager shareManager];
    
    
    // 设置服务器地址
//    [QXDataManager saveValue:ZhuJiDriverServiceUrlValue forKey:ZhuJiDriverServiceUrlKey];
    [QXDataManager saveValue:appInfoModel.AppServerAddress forKey:ZhuJiDriverServiceUrlKey];


    
    // 设置长连接地址
//     [QXDataManager saveValue:ChangLianJieDriverUrlValue forKey:ChangLianJieDriverUrlKey];
    [QXDataManager saveValue:appInfoModel.AppWebSocketAddress forKey:ChangLianJieDriverUrlKey];
    
    
    // 客服电话
//    [QXDataManager saveValue:CustomerServiceTelValue forKey:User_KeyWord_CustomerServiceTel];
    [QXDataManager saveValue:appInfoModel.AppOperatorCustomerTel forKey:User_KeyWord_CustomerServiceTel];
    
    
    // 注册微信
//     [WXApi registerApp:WeiXinPayKeyValue];
    [WXApi registerApp:appInfoModel.AppWeixinKey];
    
    // 版本号
    [QXDataManager saveValue:@"" forKey:@"versionInfo"];// 发布的时候注释掉
    
}


/**
 监听网络状态
 */
- (void)monitorNetWorkingState {
    
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    [manger startMonitoring];
    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown = -1,
         AFNetworkReachabilityStatusNotReachable = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_ReachabilityStatusNotReachable object:nil];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_ReachabilityStatusNotReachable object:nil];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_ReachabilityStatusReachableViaWWAN object:nil];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_ReachabilityStatusReachableViaWiFi object:nil];
                break;
            default:
                break;
        }
    }];
}

/**
 配置引导页
 */
- (void)configureBootPageWithApplication:(UIApplication *)application {
    
    if (![QXDataManager getValueForKey:@"ScreenOnLight"]) { // 如果没有配置屏幕常亮
        
        [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; // 默认启动常亮
    }else {
        
        NSString *isOnLight = [QXDataManager getValueForKey:@"ScreenOnLight"];
        if ([isOnLight isEqualToString:@"1"]) {
            
            [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; // 默认启动常亮
        }else {
            
            [[UIApplication sharedApplication] setIdleTimerDisabled:NO]; // 默认启动常亮
        }
    }
    
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; // 由于2.0 加密特性的影响,所以版本升级需要清空缓存信息
    NSString *appCurrentVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *appVersion = [[NSUserDefaults standardUserDefaults] valueForKey:QXAppVersion]; // 以前的版否号
    if (appVersion) { // 如果有版本号
        
        if ([appCurrentVersion compare:appVersion] == NSOrderedDescending) { // 如果版本升级那么清除以前的缓存信息
            
            [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle]bundleIdentifier]];
            [[NSUserDefaults standardUserDefaults] setValue:appCurrentVersion forKey:QXAppVersion];

        }else {
            
            [[NSUserDefaults standardUserDefaults] setValue:appCurrentVersion forKey:QXAppVersion];
        }
    }else {
        
        [[NSUserDefaults standardUserDefaults] setValue:appCurrentVersion forKey:QXAppVersion];

    }
    
    
    
    [BootPageVC initBootPageVCWithBootPageImageArray:nil startAppBlock:^{
        
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"RootViewControllerID"];
        
        [self configureDefaultAttributes];
    }];
}

/**
 配置讯飞语音播报功能
 */
- (void)configureIflyMSC {
    
    AppInfoModel *appInfoModel = [[AppManager shareManager] getAppInfo];
    
    //设置sdk的log等级，log保存在下面设置的工作路径中
    [IFlySetting setLogFile:LVL_ALL];
    
    //打开输出在console的log开关
    [IFlySetting showLogcat:YES];
    
    //设置sdk的工作路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    
    //创建语音配置,appid必须要传入，仅执行一次则可
//    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",IfMSCKeyValue];
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",appInfoModel.AppIfMSCKey];
    
    //所有服务启动前，需要确保执行createUtility
    [IFlySpeechUtility createUtility:initString];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_DirverDidEnterBackGround object:nil];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    // 如果将要处于激活状态发送通知,然后请求司机上班状态
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_DriverWorkingState object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_RefreshOrderList object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_AppEnterForceGround object:nil];
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_AppBecomeActivity object:nil];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    NSLog(@"app 将要闪退");
    
//    [NSNotificationCenter defaultCenter] postNotificationName:<#(nonnull NSNotificationName)#> object:<#(nullable id)#>
}


- (void)getConfigInfoFromHost {
    
    [DLLApiManager getH5MethodNameWithParameters:nil success:^(id data) {
        
        if ([data[@"success"] boolValue]) {
            
            NSArray *dataArr = data[@"data"];
            
            NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
            
            if ([dataArr isKindOfClass:[NSArray class]]) {
                
                if (dataArr.count > 0) {
                    
                    for (NSDictionary *dic in dataArr) {
                        
                        [tempDic setValue:dic[@"valule"] forKey:dic[@"key"]];
                    }
                }
            }
            
            [QXDataManager saveValue:tempDic[@"about"] forKey:QXHtml5Kkey_AboutDescription]; // 关于
            [QXDataManager saveValue:tempDic[@"add"] forKey:QXHtml5Kkey_AddDescription];
            [QXDataManager saveValue:tempDic[@"check"] forKey:QXHtml5Kkey_CheckDescription];
            [QXDataManager saveValue:tempDic[@"priceRules"] forKey:QXHtml5Kkey_PriceDescription]; // 价格说明
            [QXDataManager saveValue:tempDic[@"register"] forKey:QXHtml5Kkey_DriverRegisterDescription]; // 注册
            [QXDataManager saveValue:tempDic[@"ruleExplain"] forKey:QXHtml5Kkey_RulesDescription]; // 规格说明
            [QXDataManager saveValue:tempDic[@"userAgreement"] forKey:QXHtml5Kkey_UserAgreementDescription]; // 用户协议
            
        }

        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - 支付宝回调
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            
            // 支付失败
            NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
            if (resultStatus == 6001) {
                
                // 支付失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
                });
            } else if (resultStatus == 9000) {
                
                // 支付成功
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PaySuccess object:nil];
                });
            } else {
                
                // 支付失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
                });
            }
            
        }];
    }else {
        
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            
            // 支付失败
            NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
            if (resultStatus == 6001) {
                
                // 支付失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
                });
            } else if (resultStatus == 9000) {
                
                // 支付成功
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PaySuccess object:nil];
                });
            } else {
                
                // 支付失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_PayFailure object:nil];
                });
            }

            
        }];
    }else {
        
        return [WXApi handleOpenURL:url delegate:[PaymentMethodVC returnSelf]];
    }
    return YES;
}


#pragma mark - 强制升级
/**
 *  @brief  强制升级
 */
- (void)mandatoryUpgrade {
    /*
     参数:
     platform - 平台（android/ios）.
     versionNo - 版本No
     appVer - 是否为IOS企业版，由于IOS企业版已8/7于发布未设该值，故AppStore版需设值。 */
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"ios" forKey:@"platform"];
    
    AppInfoModel *appInfoModel = [AppManager shareManager].getAppInfo;
    NSString *versionInfo = appInfoModel.AppVersion;
    [dic setValue:versionInfo forKey:@"versionNo"];
    [dic setValue:[NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forKey:@"appVer"];
    
    // 发起请求
    __weak typeof(self) weakSelf = self;
    [DLLApiManager getVersionInfoWithParameters:dic success:^(id data) {
        __strong typeof(self) strongSelf = weakSelf;
        if ([data[@"success"] boolValue]) {
            
            // 获取更新状态
            BOOL isUpdate = [data[@"data"][@"update"] boolValue];
            NSString *message = data[@"data"][@"updContent"];
            strongSelf.isUsed = [data[@"data"][@"isUsed"] boolValue];
            
            // 判断师傅需要强制更新
            if (isUpdate) {
                
                strongSelf.downloadUrl = data[@"data"][@"iosUpdUrl"];
                
                if (strongSelf.isUsed) {
                    // 主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        // 如果没有
                        if (!strongSelf.updateAlertView) {
                            strongSelf.updateAlertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                            strongSelf.updateAlertView.tag = 2003;
                            [strongSelf.updateAlertView show];
                        } else {
                            [strongSelf.updateAlertView show];
                        }
                        
                    });
                }
                else {
                    // 主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        
                        
                        if (!strongSelf.updateAlertView) {
                            //强制更新
                            strongSelf.updateAlertView = [[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                            strongSelf.updateAlertView.tag = 2004;
                            [strongSelf.updateAlertView show];
                        } else {
                            
                            [strongSelf.updateAlertView show];
                        }
                        
                        
                    });
                }
            }
        }else{
            
        }
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 2003) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.downloadUrl]];
        }
    } else if (alertView.tag == 2004) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.downloadUrl]];
    }
    
}



@end
